<template>
  <div class="info-layout">
    <!-- 左侧：详细信息 -->
    <div class="info-left">
      <div class="info-section">
        <template v-if="colorData">
          <!-- 动态字段显示 -->
          <p v-for="field in validFields" :key="field.key" class="info-item">
            <strong>{{ field.label }}：</strong>
            <span v-if="field.type === 'status'">
              <span
                class="status-indicator"
                :class="getStatusBadgeClass(getFieldValue(colorData, field.key))"
              >
                {{ getStatusText(getFieldValue(colorData, field.key)) }}
              </span>
            </span>
            <span v-else-if="field.type === 'array'">
              {{
                Array.isArray(getFieldValue(colorData, field.key))
                  ? getFieldValue(colorData, field.key).join('/')
                  : getFieldValue(colorData, field.key)
              }}
            </span>
            <span v-else>
              {{ getFieldValue(colorData, field.key) }}
            </span>
          </p>
        </template>
      </div>

      <div class="detail-actions">
        <button
          class="btn btn-compact status-btn-success"
          :disabled="isProcessing"
          :class="{
            processing: isProcessing && processingButton === 'success',
            disabled: isProcessing,
          }"
          @click="handleUpdateStyleStatus('success')"
        >
          <CheckIcon :size="14" />
          匹配成功
        </button>
        <button
          class="btn btn-compact status-btn-failed"
          :disabled="isProcessing"
          :class="{
            processing: isProcessing && processingButton === 'failed',
            disabled: isProcessing,
          }"
          @click="handleUpdateStyleStatus('failed')"
        >
          <XIcon :size="14" />
          匹配失败
        </button>
        <button
          class="btn btn-compact status-btn-empty"
          :disabled="isProcessing"
          :class="{
            processing: isProcessing && processingButton === 'abandoned',
            disabled: isProcessing,
          }"
          @click="handleUpdateStyleStatus('abandoned')"
        >
          <CircleIcon :size="14" />
          标放弃
        </button>
        <div v-if="isProcessing" class="processing-hint">正在处理中...</div>
      </div>
    </div>

    <!-- 右侧：角度选择和图片预览 -->
    <div class="info-right">
      <!-- 角度缩略图 -->
      <div class="angle-thumbnails" v-if="colorData">
        <div
          v-for="angle in angleCodes"
          :key="angle"
          class="angle-thumbnail"
          :class="{
            missing: (colorData?.missingAngles || []).includes(angle),
            active: selectedAngle === angle,
          }"
          @click="selectAngle(angle)"
        >
          <span
            v-if="
              (colorData?.angles || []).includes(angle) &&
              !(colorData?.missingAngles || []).includes(angle)
            "
            >{{ getAngleDisplayName(angle) }}</span
          >
          <span v-else>!</span>
        </div>
      </div>

      <!-- 图片预览区 -->
      <div class="image-preview">
        <div
          v-if="selectedAngle && colorData && (colorData.angles || []).includes(selectedAngle)"
          class="image-container"
        >
          <img
            :src="getImageUrl(selectedAngle)"
            :alt="`${getFieldValue(colorData, 'style_code')}-${getFieldValue(
              colorData,
              'color_code'
            )}-${getAngleDisplayName(selectedAngle)}`"
            class="preview-image"
            @error="handleImageError"
          />
        </div>
        <div v-else class="preview-placeholder">
          <span>选择角度查看图片</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, ref, watch } from 'vue'
import { CheckIcon, XIcon, CircleIcon } from './icons'
import { matchingStyleStatus } from '../api/styleApi'
import { ElMessage } from 'element-plus'
import { getFullImageUrl, handleImageError } from '../utils/imageUtils'
import { getAngleDisplayName } from '../utils/angleUtils'
export default {
  name: 'ColorInfo',
  components: {
    CheckIcon,
    XIcon,
    CircleIcon,
  },
  props: {
    colorData: {
      type: Object,
      default: null,
    },
    selectedAngle: {
      type: String,
      default: '',
    },
    angleCodes: {
      type: Array,
      default: () => [],
    },
    // 动态字段配置
    fields: {
      type: Array,
      default: () => [
        { key: 'styleId', label: '款式ID', type: 'text' },
        { key: 'id', label: '颜色ID', type: 'text' },
        { key: 'productName', label: '名称', type: 'text' },
        { key: 'skuSizes', label: 'SKU尺码', type: 'array' },
        { key: 'status', label: '当前状态', type: 'status' },
      ],
    },
    // 从父组件接收处理状态
    isProcessing: {
      type: Boolean,
      default: false,
    },
    processingButton: {
      type: String,
      default: null,
    },
  },
  emits: ['select-angle', 'status-updated'],
  setup(props, { emit }) {
    // 处理状态现在由父组件统一管理，通过 props 接收

    const getStatusText = status => {
      const statusMap = {
        pending: '待匹配',
        success: '匹配成功',
        failed: '匹配失败',
        empty: '放弃',
        vectoring: '向量中',
        completed: '完成',
      }
      return statusMap[status] || status
    }
    const handleUpdateStyleStatus = async statusType => {
      if (props.isProcessing) {
        return
      }

      const colorId = getFieldValue(props.colorData, 'id')

      // 通知父组件开始处理
      emit('status-processing', colorId, statusType)

      try {
        const res = await matchingStyleStatus(colorId, statusType)

        // 检查响应格式
        if (res && res.code === 200) {
          window.$toast?.showSuccess('更新状态成功')
          // 触发父组件刷新数据
          emit('status-updated', colorId, statusType)
        } else {
          window.$toast?.showError('更新状态失败', res?.message || '未知错误')
          // 即使失败也要通知父组件处理完成
          emit('status-updated', colorId, statusType)
        }
      } catch (error) {
        console.error('更新状态失败:', error)
        window.$toast?.showError('更新状态失败', error?.message || '网络错误')
        // 即使失败也要通知父组件处理完成
        emit('status-updated', colorId, statusType)
      }
    }
    const getStatusBadgeClass = status => {
      const classMap = {
        pending: 'badge-pending',
        success: 'badge-success',
        failed: 'badge-error',
        empty: 'badge-empty',
        vectoring: 'badge-vectoring',
        completed: 'badge-completed',
      }
      return classMap[status] || 'badge-pending'
    }

    const selectAngle = angle => {
      if (
        props.colorData &&
        (props.colorData.angles || []).includes(angle) &&
        !(props.colorData.missingAngles || []).includes(angle)
      ) {
        emit('select-angle', angle)
      }
    }

    // 获取图片URL
    const getImageUrl = angle => {
      if (!props.colorData || !props.colorData.images) {
        console.log('ColorInfo: 没有图片数据', props.colorData)
        return ''
      }

      const images = props.colorData.images
      console.log('ColorInfo: 图片数据', images, '角度', angle)

      if (!Array.isArray(images)) return ''

      const image = images.find(img => img.angle === angle)
      if (!image) {
        console.log('ColorInfo: 未找到对应角度的图片', angle)
        return ''
      }

      const url = image.url
      console.log('ColorInfo: 图片URL', url)

      // 使用工具函数处理图片URL
      const fullUrl = getFullImageUrl(url)
      console.log('ColorInfo: 完整图片URL', fullUrl)
      return fullUrl
    }

    // 处理图片加载错误
    const handleImageErrorLocal = event => {
      handleImageError(event)
      // 显示占位符
      const nextElement = event.target.nextElementSibling
      if (nextElement) {
        nextElement.style.display = 'block'
      }
    }

    // 移除颜色数据变化的监听器，处理状态由父组件统一管理
    // watch(
    //   () => props.colorData,
    //   () => {
    //     isProcessing.value = false
    //     processingButton.value = null
    //   }
    // )

    // 计算属性：过滤有效的动态字段
    const dynamicFields = computed(() => {
      if (!props.colorData) return []

      return props.fields.filter(field => {
        // 检查字段是否存在且有值
        const value = props.colorData[field.key]
        return value !== undefined && value !== null && value !== ''
      })
    })

    // 过滤有效的字段
    const validFields = computed(() => {
      const fields = props.fields.filter(field => {
        // 检查字段是否存在且有值
        const value = getFieldValue(props.colorData, field.key)
        return value !== undefined && value !== null && value !== ''
      })

      // 调试：查看过滤后的字段
      console.log('ColorInfo validFields:', fields)
      console.log('ColorInfo props.fields:', props.fields)
      console.log('ColorInfo props.colorData:', props.colorData)

      return fields
    })

    // 安全地获取字段值（适配新旧数据结构）
    const getFieldValue = (obj, fieldName) => {
      if (!obj || !obj[fieldName]) {
        // 对于数组字段，返回空数组
        if (['angles', 'missingAngles'].includes(fieldName)) {
          return []
        }
        return ''
      }
      const field = obj[fieldName]
      if (typeof field === 'object' && 'value' in field) {
        return field.value || ''
      }
      return field || ''
    }

    return {
      getStatusText,
      getStatusBadgeClass,
      validFields,
      getFieldValue,
      getAngleDisplayName,
      selectAngle,
      handleUpdateStyleStatus,
      getImageUrl,
      handleImageError: handleImageErrorLocal,
    }
  },
}
</script>

<style scoped>
/* 信息标签页样式 */
.info-layout {
  display: flex;
  gap: 20px;
  height: 100%;
}

.info-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-section {
  margin-bottom: 0;
}

.info-section p {
  margin: 8px 0;
  font-size: 14px;
}

.status-indicator {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.badge-pending {
  background: #faad14;
  color: white;
}

.badge-success {
  background: var(--success-color);
  color: white;
}

.badge-error {
  background: var(--error-color);
  color: white;
}

.badge-empty {
  background: #d9d9d9;
  color: var(--text-color);
}

.badge-vectoring {
  background: #722ed1;
  color: white;
}

.badge-completed {
  background: #1890ff;
  color: white;
}

.detail-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 16px;
}

.detail-actions .btn-compact {
  justify-content: center;
}

.btn-compact {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: white;
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.2s;
  font-size: 13px;
  white-space: nowrap;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.btn-compact:hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

/* 状态按钮颜色样式 */
.status-btn-success {
  background: var(--success-color) !important;
  border-color: var(--success-color) !important;
  color: white !important;
}

.status-btn-success:hover {
  background: #389e0d !important;
  border-color: #389e0d !important;
  color: white !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(82, 196, 26, 0.3) !important;
}

.status-btn-failed {
  background: var(--error-color) !important;
  border-color: var(--error-color) !important;
  color: white !important;
}

.status-btn-failed:hover {
  background: #cf1322 !important;
  border-color: #cf1322 !important;
  color: white !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(255, 77, 79, 0.3) !important;
}

.status-btn-empty {
  background: #d9d9d9 !important;
  border-color: #d9d9d9 !important;
  color: var(--text-color) !important;
}

.status-btn-empty:hover {
  background: #a6a6a6 !important;
  border-color: #a6a6a6 !important;
  color: var(--text-color) !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(217, 217, 217, 0.3) !important;
}

/* 处理中状态样式 - 呼吸式效果 */
.btn-compact.processing {
  position: relative;
  overflow: hidden;
  cursor: not-allowed;
  animation: buttonBreathing 1.5s ease-in-out infinite;
  border: 2px solid var(--primary-color);
  box-shadow: 0 0 15px rgba(24, 144, 255, 0.4);
}

@keyframes buttonBreathing {
  0%,
  100% {
    background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 50%, #e6f7ff 100%);
  }
  50% {
    background: linear-gradient(135deg, #bae7ff 0%, #91d5ff 50%, #bae7ff 100%);
  }
}

/* 禁用状态样式 - 所有按钮同时置灰 */
.btn-compact.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

.btn-compact.disabled:hover {
  transform: none !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
}

@keyframes shimmer {
  0% {
    left: -100%;
  }
  100% {
    left: 100%;
  }
}

/* 处理中提示样式 */
.processing-hint {
  margin-top: 8px;
  font-size: 12px;
  color: var(--text-secondary);
  text-align: center;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
}

.angle-thumbnails {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.angle-thumbnail {
  width: 29px;
  height: 29px;
  border: 2px solid var(--border-color);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  background: var(--success-color);
  color: white;
  border-color: var(--success-color);
}

.angle-thumbnail.missing {
  background: #f0f0f0;
  color: var(--text-secondary);
  border-color: #d9d9d9;
}

.angle-thumbnail.active {
  background: var(--primary-color);
  border-color: var(--primary-color);
}

.image-preview {
  flex: 1;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  aspect-ratio: 1;
  max-width: 100%;
  overflow: hidden;
}

.image-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: var(--border-radius);
}

.preview-placeholder {
  color: var(--text-secondary);
  font-size: 14px;
}
</style>
